"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  ResizablePanel,
  ResizablePanelGroup,
  ResizableHandle,
} from "@/components/ui/resizable";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { FiSave, FiX, FiTag, FiPlus } from "react-icons/fi";
import MarkdownEditor from "@/components/markdown-editor";
import MarkdownPreview from "@/components/markdown-preview";

// 系统中的角色数据
const roles = [
  { id: "admin", name: "管理员" },
  { id: "tech", name: "技术人员" },
  { id: "product", name: "产品经理" },
  { id: "finance", name: "财务人员" },
  { id: "hr", name: "人事专员" },
  { id: "marketing", name: "市场专员" },
];

export default function NewDocumentPage() {
  const router = useRouter();
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [content, setContent] = useState("");
  const [viewableRoles, setViewableRoles] = useState<string[]>(["admin"]); // 默认管理员可见
  const [tags, setTags] = useState<string[]>([]);
  const [newTag, setNewTag] = useState("");
  const [showRoleDropdown, setShowRoleDropdown] = useState(false);

  // 处理添加标签
  const handleAddTag = () => {
    if (newTag.trim() && !tags.includes(newTag.trim())) {
      setTags([...tags, newTag.trim()]);
      setNewTag("");
    }
  };

  // 处理移除标签
  const handleRemoveTag = (tagToRemove: string) => {
    setTags(tags.filter((tag) => tag !== tagToRemove));
  };

  // 处理添加/移除角色
  const toggleRole = (roleId: string) => {
    if (viewableRoles.includes(roleId)) {
      // 如果已选择，则移除角色（但至少保留一个角色）
      if (viewableRoles.length > 1) {
        setViewableRoles(viewableRoles.filter((id) => id !== roleId));
      }
    } else {
      // 如果未选择，则添加角色
      setViewableRoles([...viewableRoles, roleId]);
    }
  };

  // 获取角色名称
  const getRoleName = (roleId: string) => {
    return roles.find((role) => role.id === roleId)?.name || roleId;
  };

  // 处理保存文档
  const handleSaveDocument = () => {
    if (!title.trim()) {
      alert("请输入文档标题");
      return;
    }

    // 这里将添加发送到后端API的逻辑
    console.log("保存文档:", {
      title,
      description,
      content,
      viewableRoles,
      tags,
    });

    // 模拟保存成功后返回文档列表
    setTimeout(() => {
      router.push("/documents");
    }, 500);
  };

  // 取消创建文档
  const handleCancel = () => {
    if (content || title || description) {
      if (confirm("确定要取消创建吗？所有未保存的内容将丢失。")) {
        router.push("/documents");
      }
    } else {
      router.push("/documents");
    }
  };

  return (
    <div className='container mx-auto px-4 py-6'>
      <div className='flex justify-between items-center mb-6'>
        <h1 className='text-2xl font-bold text-gray-800 dark:text-white'>
          创建新文档
        </h1>
        <div className='flex space-x-2'>
          <Button
            variant='outline'
            onClick={handleCancel}
            className='flex items-center'
          >
            <FiX className='mr-2' /> 取消
          </Button>
          <Button
            onClick={handleSaveDocument}
            className='bg-blue-500 hover:bg-blue-600 text-white flex items-center'
          >
            <FiSave className='mr-2' /> 保存文档
          </Button>
        </div>
      </div>

      <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6 mb-6'>
        <div className='space-y-4'>
          <div>
            <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
              文档标题 <span className='text-red-500'>*</span>
            </label>
            <Input
              type='text'
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder='输入文档标题'
              className='w-full'
            />
          </div>

          <div>
            <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
              文档描述
            </label>
            <Input
              type='text'
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder='简要描述文档内容'
              className='w-full'
            />
          </div>

          <div className='flex flex-col sm:flex-row gap-4'>
            <div className='w-full sm:w-1/2'>
              <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
                可查看角色 <span className='text-red-500'>*</span>
              </label>
              <div className='relative'>
                <button
                  className='w-full flex items-center justify-between px-3 py-2 text-sm border rounded-md shadow-sm bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600'
                  onClick={() => setShowRoleDropdown(!showRoleDropdown)}
                >
                  <span>
                    {viewableRoles.length > 0
                      ? `已选择 ${viewableRoles.length} 个角色`
                      : "选择可查看角色"}
                  </span>
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    width='16'
                    height='16'
                    viewBox='0 0 24 24'
                    fill='none'
                    stroke='currentColor'
                    strokeWidth='2'
                    strokeLinecap='round'
                    strokeLinejoin='round'
                    className={`transition-transform ${
                      showRoleDropdown ? "rotate-180" : ""
                    }`}
                  >
                    <path d='m6 9 6 6 6-6' />
                  </svg>
                </button>

                {showRoleDropdown && (
                  <div className='absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg'>
                    <ul className='py-1'>
                      {roles.map((role) => (
                        <li
                          key={role.id}
                          className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 ${
                            viewableRoles.includes(role.id)
                              ? "bg-gray-100 dark:bg-gray-700 font-medium"
                              : ""
                          }`}
                          onClick={() => {
                            toggleRole(role.id);
                          }}
                        >
                          <div className='flex items-center'>
                            <input
                              type='checkbox'
                              checked={viewableRoles.includes(role.id)}
                              onChange={() => {}}
                              className='mr-2'
                            />
                            {role.name}
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>

              <div className='flex flex-wrap gap-2 mt-2'>
                {viewableRoles.map((roleId, index) => (
                  <span
                    key={index}
                    className='inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300 border border-green-200 dark:border-green-800'
                  >
                    {getRoleName(roleId)}
                    <button
                      type='button'
                      className='ml-1 h-4 w-4 rounded-full inline-flex items-center justify-center text-green-400 hover:text-green-500'
                      onClick={() =>
                        viewableRoles.length > 1 && toggleRole(roleId)
                      }
                    >
                      <span className='sr-only'>移除角色</span>
                      <FiX className='h-3 w-3' />
                    </button>
                  </span>
                ))}
              </div>
            </div>

            <div className='w-full sm:w-1/2'>
              <label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1'>
                文档标签
              </label>
              <div className='flex items-center gap-2'>
                <Input
                  type='text'
                  value={newTag}
                  onChange={(e) => setNewTag(e.target.value)}
                  placeholder='添加标签'
                  className='flex-1'
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      handleAddTag();
                    }
                  }}
                />
                <Button
                  size='icon'
                  onClick={handleAddTag}
                  className='flex-shrink-0'
                >
                  <FiPlus />
                </Button>
              </div>
              <div className='flex flex-wrap gap-2 mt-2'>
                {tags.map((tag, index) => (
                  <span
                    key={index}
                    className='inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border border-blue-200 dark:border-blue-800'
                  >
                    <FiTag className='mr-1 h-3 w-3' />
                    {tag}
                    <button
                      type='button'
                      className='ml-1 h-4 w-4 rounded-full inline-flex items-center justify-center text-blue-400 hover:text-blue-500'
                      onClick={() => handleRemoveTag(tag)}
                    >
                      <span className='sr-only'>移除标签</span>
                      <FiX className='h-3 w-3' />
                    </button>
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden'>
        <div className='p-4 border-b'>
          <h2 className='text-lg font-medium'>文档内容</h2>
        </div>

        <ResizablePanelGroup direction='horizontal' className='min-h-[500px]'>
          <ResizablePanel defaultSize={50}>
            <div className='p-4 h-full'>
              <MarkdownEditor
                initialContent=''
                onChange={setContent}
                onSave={handleSaveDocument}
              />
            </div>
          </ResizablePanel>

          <ResizableHandle withHandle />

          <ResizablePanel defaultSize={50}>
            <div className='p-4 h-full overflow-auto'>
              <div className='border-b pb-2 mb-4'>
                <h3 className='font-medium'>预览</h3>
              </div>
              <MarkdownPreview content={content} />
            </div>
          </ResizablePanel>
        </ResizablePanelGroup>
      </div>
    </div>
  );
}
